import java.util.Arrays;

public class MyArrayListCourse {
    private int[] elem;
    private int usedSize;
    private static final int DEFAUT_SIZE = 2;
    public MyArrayListCourse(){
        this.elem = new int[DEFAUT_SIZE];
    }
    public MyArrayListCourse(int capacity){
        this.elem = new int[capacity];
    }
    //增加元素
    public void add(int num){
        //增加元素之前，需要先判断数组中是否已经被存满
        // 如果存满了需要先扩容
        if(isFull()){
            this.elem = Arrays.copyOf(this.elem, 2 * this.elem.length);
        }
        this.elem[this.usedSize] = num;
        this.usedSize++;
    }
    //在pos位置新增元素
    public void add(int pos, int num){
        //判断pos位置是否合法
        if(pos < 0 || pos > this.usedSize){
            throw new PosIlegalException(pos + "位置不合法");
        }
        //判断是否需要扩容
        if(isFull()){
            this.elem = Arrays.copyOf(this.elem, 2 * this.elem.length);
        }
        //挪位置
        for (int i = this.usedSize - 1; i >= pos; i--) {
            this.elem[i + 1] = this.elem[i];
        }
        //放新元素
        this.elem[pos] = num;
        this.usedSize++;
    }
    //找元素
    public boolean contains(int toFind){
        for (int i = 0; i < this.usedSize; i++) {
            if(this.elem[i] == toFind){
                return true;
            }
        }
        return false;
    }
    //查找某个元素的位置
    public int indexOf(int toFind){
        for (int i = 0; i < this.usedSize; i++) {
            if(this.elem[i] == toFind){
                return i;
            }
        }
        return -1;
    }
    //根据下标找某个元素
    public int get(int pos){
        checkPos(pos);
        return this.elem[pos];
    }
    public void set(int pos, int value){
        checkPos(pos);
        this.elem[pos] = value;
    }
    private void checkPos(int pos){
        //判断pos位置是否合法
        if(pos < 0 || pos >= this.usedSize){
            throw new PosIlegalException(pos + "位置不合法");
        }
    }
    public boolean isFull(){
        if(this.usedSize == this.elem.length){
            return true;
        }
        return false;
    }
    //删除某个第一次出现的元素
    public void remove(int toRemove){
        int index = indexOf(toRemove);
        if(index == -1){
            return;
        }
        for (int i = index; i < this.usedSize - 1; i++) {
            this.elem[i] = this.elem[i + 1];
        }
        this.usedSize--;
    }

    //获取顺序表长度
    public int size(){
        return this.usedSize;
    }

    //打印顺序表
    public void show(){
        for (int i = 0; i < usedSize; i++) {
            System.out.print(this.elem[i] + " ");
        }
        System.out.println();
    }

    public void clear(){
        this.usedSize = 0;
    }
}
